package com.google.cbmgraph.data;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.util.Log;

public class GetData {

	
	static final String NODE = "doc";
	static final String ENTRY = "arr";
	static final String TYPE = "int";
	static final String MONTHS = "MONTHS_SURVIVED";
	static final String PERCENT = "PERCENT_SURVIVED";

	private static final String TAG = "GetData";
	private static final int CONNECTION_TIMEOUT = 0;

	private static final int WAIT_RESPONSE_TIMEOUT = 0;
	/**
	 * Grabs data from the server
	 * @return xml string of data
	 * @throws Exception
	 */
	public static String grabData()throws Exception {
//		Log.d(TAG, "entered class");
	    String xml="";
	    try {
	    	Log.d(TAG, "setting parameters");
	    	HttpParams httpParameters = new BasicHttpParams();
	    	HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
	    	HttpConnectionParams.setSoTimeout(httpParameters, WAIT_RESPONSE_TIMEOUT);
	    	HttpConnectionParams.setTcpNoDelay(httpParameters, true);
	        HttpClient client = new DefaultHttpClient(httpParameters);
	        HttpGet request = new HttpGet();
	        request.setURI(new URI(DataSource.URL));
	        HttpResponse response = client.execute(request);
            HttpEntity httpEntity = response.getEntity();
            xml = EntityUtils.toString(httpEntity);
	    }catch (UnsupportedEncodingException e) {
            Log.d(TAG,e.toString());
        } catch (ClientProtocolException e) {
        	Log.d(TAG,e.toString());
        } catch (IOException e) {
        	Log.d(TAG,e.toString());
        }
	    return xml;
	}
	/**
	 * Helper XML parser see source for more details
	 * @return Document object
	 */
	// taken from http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/
	private static Document getDomElement(String xml){
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
 
            DocumentBuilder db = dbf.newDocumentBuilder();
 
            InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is);
 
            } catch (ParserConfigurationException e) {
//                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
//                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
//                Log.e("Error: ", e.getMessage());
                return null;
            }
                // return DOM
            return doc;
    }
	/**
	 * Parses the XML into an arraylist of points
	 * @return ArrayList of coordinates
	 */
	public static ArrayList<int[]> parseXML(String xmlData) {
		ArrayList<int[]> points = new ArrayList<int[]>();
		Document doc = getDomElement(xmlData);
		// data is separated by "doc" tags
		NodeList nl = doc.getElementsByTagName(NODE);
		for (int i = 0; i < nl.getLength(); i++){
			int point[] = new int[2];
			Element element = (Element)nl.item(i);
			NodeList nodes = element.getElementsByTagName(TYPE);
			Element nodeElement = (Element)nodes.item(0);
			Element secondElement = (Element)nodes.item(1);
			String test = getValue(nodeElement,TYPE);
			String test2 = getValue(secondElement,TYPE);
			point[0]=Integer.parseInt(test);
			point[1]=Integer.parseInt(test2);
			points.add(point);
		}
		
		return points;
	}
	// parser help function
	private static String getValue(Element item, String str) {
		NodeList n = item.getElementsByTagName(str);
		return getElementValue(n.item(0));
	}
	// parser help function
	private static final String getElementValue( Node elem ) {
		     Node child;
		     if( elem != null){
		         if (elem.hasChildNodes()){
		             for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
		                 if( child.getNodeType() == Node.TEXT_NODE  ){
		                     return child.getNodeValue();
		                 }
		             }
		         }
		     }
		     return "";
	  }	

}
